#!/bin/bash

declare -a COMMON_VARIABLES
COMMON_VARIABLES=(`perl $TWMFOLDER/bin/get_varMultipleValue.pl gawk iptables grep netstat _DEFAULT_`)
gawk=${COMMON_VARIABLES[0]}
iptables=${COMMON_VARIABLES[1]}
grep=${COMMON_VARIABLES[2]}
netstat=${COMMON_VARIABLES[3]}

ACTION="D"
if [ "$1" = "A" ] || [ "$1" = "I" ]; then
	ACTION="I"
fi
shift

interface=`netstat -nr | grep UG | grep 0.0.0.0 | $gawk '{print $8}'`

perl $TWMFOLDER/modules/vpn_traffic/get_data.pl | while read ip intf rip; do
	if [ "$intf" = '*' ]; then
		intf="$interface"
	fi
	if [ "$rip" = '*' ]; then
		src=''
		dst=''
	else
		src="--src $rip"
		dst="--dst $rip"
	fi

	$iptables -t nat -$ACTION POSTROUTING -p icmp -s $ip -o $intf $dst -j MASQUERADE
	$iptables -t nat -$ACTION POSTROUTING -p gre -s $ip -o $intf $dst -j MASQUERADE
	$iptables -t nat -$ACTION POSTROUTING -p udp -s $ip -o $intf $dst -j MASQUERADE
	if [ "$src" != "" ]; then
		$iptables -t nat -$ACTION PREROUTING -i $intf -p gre $src -j DNAT --to $ip
	fi

done


exit 0